package com.ruoyi.system.service.impl;

import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;

import com.ruoyi.common.core.domain.model.LoginUser;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.LeaveapplyMapper;
import com.ruoyi.system.domain.Leaveapply;
import com.ruoyi.system.service.ILeaveapplyService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;
import static org.apache.commons.lang3.SystemUtils.getUserName;

/**
 * 请假Service业务层处理
 * 
 * @author shenzhanwang
 * @date 2022-04-02
 */
@Service
@Transactional
public class LeaveapplyServiceImpl implements ILeaveapplyService 
{
    @Resource
    private LeaveapplyMapper leaveapplyMapper;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    IdentityService identityService;

    @Resource
    HistoryService historyService;

    /**
     * 查询请假
     * 
     * @param id 请假主键
     * @return 请假
     */
    @Override
    public Leaveapply selectLeaveapplyById(Long id)
    {
        return leaveapplyMapper.selectLeaveapplyById(id);
    }

    /**
     * 查询请假列表
     * 
     * @param leaveapply 请假
     * @return 请假
     */
    @Override
    @DataScope(deptAlias = "u")
    public List<Leaveapply> selectLeaveapplyList(Leaveapply leaveapply)
    {
        //实现当前部门查看，和userId下查看；admin不受两者控制；班组长、站长角色不受userId控制
        return leaveapplyMapper.selectLeaveapplyList(leaveapply);
    }

    /**
     * 新增请假
     * 
     * @param leaveapply 请假
     * @return 结果
     */
    @Override
    public int insertLeaveapply(Leaveapply leaveapply)
    {
        int rows = leaveapplyMapper.insertLeaveapply(leaveapply);
        // identityService来设置当前操作的用户ID为请假申请人的ID。
        // 这一步是为了确保在后续的操作中，流程实例能够知道是谁发起的这个流程
        identityService.setAuthenticatedUserId(leaveapply.getUserId());
        //设置流程变量
        HashMap<String, Object> variables = new HashMap<>();
        variables.put("applyuserid", leaveapply.getUserId());
        variables.put("deptleader", leaveapply.getDeptleader());
        //使用RuntimeService来启动一个新的流程实例 （模型标识，业务号）
        runtimeService.startProcessInstanceByKey("leave", String.valueOf(leaveapply.getId()), variables);
        // 查询任务并自动完成第一个任务
        Task autoTask = taskService.createTaskQuery().processDefinitionKey("leave").processInstanceBusinessKey(String.valueOf(leaveapply.getId())).singleResult();
        taskService.complete(autoTask.getId());
        return rows;
    }

    /**
     * 新增我的请假
     *
     * @param leaveapply 请假
     * @return 结果
     */
    @Override
    public int insertmyLeaveapply(Leaveapply leaveapply)
    {

        int rows = leaveapplyMapper.insertLeaveapply(leaveapply);
        // identityService来设置当前操作的用户ID为请假申请人的ID。
        // 这一步是为了确保在后续的操作中，流程实例能够知道是谁发起的这个流程
        identityService.setAuthenticatedUserId(leaveapply.getUserId());
        //设置流程变量
        HashMap<String, Object> variables = new HashMap<>();
        variables.put("applyuserid", leaveapply.getUserId());//登录账号
        variables.put("deptleader", leaveapply.getDeptleader());
        if("年假".equals(leaveapply.getLeaveType()) || "病假".equals(leaveapply.getLeaveType())){
            //使用RuntimeService来启动一个新的流程实例 （模型标识，业务号）
            runtimeService.startProcessInstanceByKey("test", String.valueOf(leaveapply.getId()), variables);
            // 查询任务并自动完成第一个任务
            Task autoTask = taskService.createTaskQuery().processDefinitionKey("test").processInstanceBusinessKey(String.valueOf(leaveapply.getId())).singleResult();
            taskService.complete(autoTask.getId());
        }
        return rows;
    }

    /**
     * 修改请假
     * 
     * @param leaveapply 请假
     * @return 结果
     */
    @Override
    public int updateLeaveapply(Leaveapply leaveapply)
    {
        return leaveapplyMapper.updateLeaveapply(leaveapply);
    }

    /**
     * 批量删除请假
     * 
     * @param ids 需要删除的请假主键
     * @return 结果
     */
    @Override
    public int deleteLeaveapplyByIds(String ids)
    {
        String[] keys = Convert.toStrArray(ids);
        for (String key : keys) {
            ProcessInstance process = runtimeService.createProcessInstanceQuery().processDefinitionKey("leave").processInstanceBusinessKey(key).singleResult();
            if (process != null) {
                runtimeService.deleteProcessInstance(process.getId(), "删除");
            }
            // 删除历史数据
            HistoricProcessInstance history = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("leave").processInstanceBusinessKey(key).singleResult();
            if (history != null){
                historyService.deleteHistoricProcessInstance(history.getId());
            }
            leaveapplyMapper.deleteLeaveapplyById(Long.parseLong(key));
        }
        return keys.length;
    }

    /**
     * 删除请假信息
     * 
     * @param id 请假主键
     * @return 结果
     */
    @Override
    public int deleteLeaveapplyById(Long id)
    {
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processDefinitionKey("test").processInstanceBusinessKey(String.valueOf(id)).singleResult();
        if (process != null) {
            runtimeService.deleteProcessInstance(process.getId(), "删除");
        }
        // 删除历史数据
        HistoricProcessInstance history = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("test").processInstanceBusinessKey(String.valueOf(id)).singleResult();
        if (history != null){
            historyService.deleteHistoricProcessInstance(history.getId());
        }
        return leaveapplyMapper.deleteLeaveapplyById(id);
    }

    /**
     * 批量删除请假
     *
     * @param ids 需要删除的请假主键
     * @return 结果
     */
    @Override
    public int deleteMyLeaveapplyByIds(String ids)
    {
        String userName = getLoginUser().getUser().getUserName();
        Boolean flag = false;
        List<SysRole> roles = getLoginUser().getUser().getRoles();
        for (SysRole role : roles) {
            String roleKey = role.getRoleKey();
            if("admin".equals(roleKey) || "bzzsp".equals(roleKey) || "zzsp".equals(roleKey)){//超级管理员，班组长和站长
                flag = true;
            }
        }
        String[] keys = Convert.toStrArray(ids);
        for (String key : keys) {
            Leaveapply leaveapply = leaveapplyMapper.selectLeaveapplyById(Long.valueOf(key));
            if (userName.equals(leaveapply.getUserId()) || flag) {//除了超级管理员，班组长和站长可以删除全部记录，其他用户只能删除自己
                if ("待审批".equals(leaveapply.getSpres())) {
                    ProcessInstance process = runtimeService.createProcessInstanceQuery().processDefinitionKey("test").processInstanceBusinessKey(key).singleResult();
                    if (process != null) {
                        runtimeService.deleteProcessInstance(process.getId(), "删除");
                    }
                    // 删除历史数据
                    HistoricProcessInstance history = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("test").processInstanceBusinessKey(key).singleResult();
                    if (history != null) {
                        historyService.deleteHistoricProcessInstance(history.getId());
                    }
                    leaveapplyMapper.deleteLeaveapplyById(Long.parseLong(key));
                } else {
                    return 0;
                }
            }else{
                return 0;
            }
        }
        return keys.length;
    }

    public int getProcessIdByLeaveId(String id){
        if (id != null) {
            ProcessInstance process = runtimeService.createProcessInstanceQuery().processDefinitionKey("test").processInstanceBusinessKey(id).singleResult();
            if (process != null) {
                return Integer.parseInt(process.getId());
            }
        }
        return 0;
    }
}
